/**
 * File: Node2ContigFilePositionController.java
 * Created by: mhaimel
 * Created on: May 4, 2010
 * CVS:  $Id: Node2ContigFilePositionController.java 1.0 May 4, 2010 4:01:32 PM mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.graph;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import uk.ac.ebi.curtain.controller.SingleSubmitController;
import uk.ac.ebi.curtain.service.IdentifierStore;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.concurrent.UtilsCollect;
import uk.ac.ebi.curtain.utils.data.FileType;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.file.EntryMapper;
import uk.ac.ebi.curtain.utils.file.EntryMapperBean;
import uk.ac.ebi.curtain.utils.file.FileInfo;

/**
 * @author mhaimel
 *
 */
public class Node2ContigFilePositionController extends SingleSubmitController<Serializable, Serializable> {
	
	public static final String KEY = "NODE_2_FILEPOS";

	@Override
	protected void singleSubmit(List<Serializable> inputList) {
		final ConcurrentMap<Long, Long> map = UtilsCollect.newConcurrentMap();
		final IdentifierStore<String, Integer> idx = getContext().getContigIndex();
		for(FileInfo fi : getContext().getArguments().getFiles(ReadType.Contig, FileType.values())){
			fi.parse(new EntryMapper() {
				
				@Override
				public void mapEntry(EntryMapperBean bean) {
					String id = bean.getId();
					long fp = bean.getFilePosition();
					Integer ctgId = idx.getIdentifier(id);
					long gfp = getContext().getGlobalFileIndex().getStartPosition(bean.getInfo());
					gfp += fp;
					if(null == ctgId){
						throw new CurtainUncheckedException("Contig not registered in nodes: " + id);
					}
					map.put(ctgId.longValue(), gfp);
				}
			});
		}
		getContext().getScratchBoard().put(KEY, map);
		for(Serializable s : inputList){
			submit(s);
		}
	}
}
